package leetcode.f1t100;

/**
 * 两串二进制字符串相加
 * https://leetcode.com/problems/add-binary/
 *
 * @Author lichongxiao
 * @Date 2022/11/22 15:47
 */
public class Q67_AddBinary {
    public String addBinary(String a, String b) {
        char[] charsA = a.toCharArray(), charsB = b.toCharArray();
        int indexA = charsA.length - 1, indexB = charsB.length - 1;
        StringBuilder sb = new StringBuilder();
        boolean up = false;
        while (indexA >= 0 && indexB >= 0){
            if(charsA[indexA] == charsB[indexB]){
                sb.insert(0,up ? '1':'0');
                up = charsA[indexA] == '1';
            }else{
                sb.insert(0,up?'0':'1');
            }
            indexA--;
            indexB--;
        }
        if(indexB >= 0){
            indexA = indexB;
            charsA = charsB;
        }
        while(indexA>=0){
            if(!up){
                sb.insert(0,charsA[indexA]);
            }else if(charsA[indexA] == '1'){
                sb.insert(0,'0');
            }else {
                sb.insert(0,'1');
                up =false;
            }
            indexA--;
        }
        if(up){
            sb.insert(0,'1');
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Q67_AddBinary bean = new Q67_AddBinary();
        int testN = 100;
        int testMax = 1000;
        for (int i = 0; i <testN ; i++) {
            int a = Double.valueOf(Math.random()*testMax).intValue();
            int b = Double.valueOf(Math.random()*testMax).intValue();
            if(!Integer.toBinaryString(a+b).equals(bean.addBinary(Integer.toBinaryString(a),Integer.toBinaryString(b)))){
                System.out.println("fail");
                System.out.println(Integer.toBinaryString(a));
                System.out.println(Integer.toBinaryString(b));
                System.out.println(Integer.toBinaryString(a+b));
                System.out.println(bean.addBinary(Integer.toBinaryString(a),Integer.toBinaryString(b)));
                break;
            }
        }
        System.out.println("finish");
    }
}
